package com.e.dianshang.service.impl;

import com.e.dianshang.mapper.OrderMapper;
import com.e.dianshang.mapper.PayMapper;
import com.e.dianshang.service.PayService;
import com.e.dianshang.utils.BusinessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Service("payService")
public class PayServiceImpl implements PayService {

    @Resource
    PayMapper payMapper;
    @Resource
    OrderMapper orderMapper;

    // java要操作redis  借助于RedisTemplate
    @Resource
    RedisTemplate<String,Object> redisTemplate;

    @Override
    @Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,rollbackFor = {Throwable.class})
    public int insertPay(Map map) throws BusinessException {
        Object addId = map.get("addId");
        if (addId==null || addId.equals("")){
            throw new BusinessException("你还没填收货地址哟~~~");
        }
        // 获取当前日期
        Date date = new Date();

        map.put("createDate",date);

        // 设置获取时间格式
        SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSSS");
        // 获取string类型时间
        String format = sim.format(date);
        // 去掉时间中的连接符号
        String s = format.replaceAll("[[\\s-:punct:]]", "");
//        String uuid = UUID.randomUUID().toString().replace("-","");
        String unique=("LG" + s);

        map.put("unique", "LG" + s);


        // 将数据保存在redis服务器上, 15分钟有效
        // 1.利用RedisTemplate绑定要操作的数据类型  生成对应的操作符对象
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
        // 2.利用操作符对象对该类型数据赋值
//                    String phone = "12312333333";
//                    String captcha = code;
        // 生成一个用手机号作为key的string，设置生存时间
//        operations.set("sms:" + phone, code, 15, TimeUnit.MINUTES);
        String openid = (String) map.get("openid");

        operations.set(openid+":"+unique, unique,15, TimeUnit.MINUTES);
        // 设置生存时间


        map.put("state",5);

        map.put("payType",false);

        List<Map> list = (List<Map>) map.get("list");
        for (int i=0;i<list.size();i++){
            list.get(i).put("unique",unique);
        }
////        System.out.println(list);
//        map.remove("list");

        payMapper.insertPayPurchased(list);

        return payMapper.insertPay(map);

    }




}
